import axios from 'axios';
import config from './config';
import CryptoJS from 'crypto-js';

const PASSWORD_SECRET = 'password_secret_456';

const apiClient = axios.create({
  baseURL: config.API_BASE_URL,
  headers: { 'Content-Type': 'application/json' }
});

// **用户登录**
export const login = async (username, password) => {
  try {
    const encryptedPassword = CryptoJS.AES.encrypt(password, PASSWORD_SECRET).toString();

    const response = await apiClient.post('/login', {
      username,
      password: encryptedPassword
    });

    const token = response.headers['authorization'];
    const userId = response.data.userId; // 获取后端返回的用户ID
    // console.log(userId,'userId');

    if (token) {
      localStorage.setItem('token', token);
      localStorage.setItem('userId', userId); // 存储用户ID
    }

    return { success: true, userId };
  } catch (error) {
    console.error('Login API Error:', error);
    return { success: false, message: error.response?.data?.message || '登录失败' };
  }
};


// **用户注册**
export const register = async (username, email, password) => {
  try {
    const encryptedPassword = CryptoJS.AES.encrypt(password, PASSWORD_SECRET).toString();

    const response = await apiClient.post('/register', {
      username,
      email,
      password: password
    });

    return response.data; // { success: true, message: "注册成功" }
  } catch (error) {
    console.error('Register API Error:', error);
    return { success: false, message: error.response?.data?.message || '注册失败' };
  }
};

// 获取用户列表接口
// 获取用户列表接口
export const getUsersArr = async (userId) => {
  try {
    // 在请求中添加 userId 查询参数
    const response = await apiClient.get('/users', { params: { userId } });
    return response.data;
  } catch (error) {
    console.error('Get Users API Error:', error);
    return {
      success: false,
      message: error.response?.data?.message || '获取用户列表失败',
    };
  }
};
// 删除管理员接口
// 删除管理员接口
export const deleteAdminUser = async (id) => {
  try {
    // 发送 DELETE 请求删除用户
    const response = await apiClient.delete(`/deleteAdminUser/${id}`);

    return response.data;

  } catch (error) {
    console.error('删除用户失败:', error);

    return {
      success: false,
      message: error.response?.data?.message || '删除用户失败',
    };
  }
};
// 删除普通用户接口
export const deleteRegularUsers = async (id) => {
  try {
    // 发送 DELETE 请求删除用户
    const response = await apiClient.delete(`/deleteUser/${id}`);

    return response.data;

  } catch (error) {
    console.error('删除用户失败:', error);

    return {
      success: false,
      message: error.response?.data?.message || '删除用户失败',
    };
  }
};
//获取log日志接口
export const getLogData = async () => {
  try {
    const response = await apiClient.get('/logs');  // 请求 /getWordsData API
    return response.data;
  } catch (error) {
    console.error('获取log数据失败:', error);
    return {
      success: false,
      message: error.response?.data?.message || '获取log数据失败',
    };
  }
};
//获取学习log日志接口
export const getAllStudyLogs = async () => {
  try {
    const response = await apiClient.get('/getAllStudyLogs');  // 请求 /getAllStudyLogs API
    return response.data;
  } catch (error) {
    console.error('获取学习log数据失败:', error);
    return {
      success: false,
      message: error.response?.data?.message || '获取学习log数据失败',
    };
  }
};
//获取5条学习log日志接口
export const getRecentStudyLogsApi = async () => {
  try {
    const response = await apiClient.get('/api/recent-study-logs');  // 请求 /api/recent-study-logs API
    return response.data;
  } catch (error) {
    console.error('获取学习log数据失败:', error);
    return {
      success: false,
      message: error.response?.data?.message || '获取学习log数据失败',
    };
  }
};
// 封装修改用户状态的 API 调用
export const updateUserStatus = async (id, status) => {
  try {
    const response = await apiClient.put(`/updateUserStatus/${id}`, { status });

    return response.data;
  } catch (error) {
    console.error('修改用户状态失败:', error);
    return {
      success: false,
      message: error.response?.data?.message || '修改失败，请重试'
    };
  }
};



// 获取用户数据接口
export const getUserData = async (userId) => {
  // console.log(userId, 'userIdsxsaxas');
  try {
    // 发送 GET 请求获取用户数据
    const response = await apiClient.get(`/admins/${userId}`);
    // console.log(response.data, 'response');
    // 返回用户数据
    return response.data;

  } catch (error) {
    console.error('获取用户数据失败:', error);

    // 返回错误信息
    return {
      success: false,
      message: error.response?.data?.message || '获取用户数据失败',
    };
  }
};

// 获取单词数据
export const getWordsData = async () => {
  try {
    const response = await apiClient.get('/getWordsData');  // 请求 /getWordsData API
    return response.data;
  } catch (error) {
    console.error('获取单词数据失败:', error);
    return {
      success: false,
      message: error.response?.data?.message || '获取单词数据失败',
    };
  }
};

// **获取受保护数据**
export const getProtectedData = async () => {
  const token = localStorage.getItem('token');
  if (!token) {
    return { success: false, message: '未登录' };
  }

  try {
    const response = await apiClient.get('/protected', {
      headers: { Authorization: `Bearer ${token}` }
    });
    return response.data;
  } catch (error) {
    console.error('Protected API Error:', error);
    return { success: false, message: error.response?.data?.message || '请求失败' };
  }
};

// **请求未学习过的单词 (Custom Limit)**
export const getUnlearnedWords = async (userId, limit) => {
  const token = localStorage.getItem('token');

  // If the token doesn't exist, return an error
  if (!token) {
    return { success: false, message: '未登录' };
  }

  // If the limit is not a number or is less than 1, set a default limit
  if (isNaN(limit) || limit < 1) {
    limit = 10; // Default to 10 if the limit is invalid
  }

  try {
    const response = await apiClient.post('/get-unlearned-words', {
      user_id: userId,
      limit: limit
    }, {
      headers: { Authorization: `Bearer ${token}` }
    });

    return response.data; // Returns the list of unlearned words
  } catch (error) {
    console.error('Get Unlearned Words API Error:', error);
    return { success: false, message: error.response?.data?.message || '请求失败' };
  }
};

// **提交学习过的单词**
export const saveLearnedWords = async (userId, learnedWords) => {
  const token = localStorage.getItem('token');

  if (!token) {
    return { success: false, message: '未登录' };
  }

  if (!Array.isArray(learnedWords) || learnedWords.length === 0) {
    return { success: false, message: '学习记录不能为空' };
  }

  try {
    const response = await apiClient.post('/insert-user-words', {
      userId,
      learnedWords
    }, {
      headers: { Authorization: `Bearer ${token}` }
    });

    return response.data; // { success: true, message: "学习记录插入成功" }
  } catch (error) {
    console.error('Save Learned Words API Error:', error);
    return { success: false, message: error.response?.data?.message || '提交学习记录失败' };
  }
};


// **查询用户学习统计信息**
export const getUserStats = async (userId) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      return { success: false, message: '请先登录' };
    }

    // 发送 GET 请求获取学习统计信息
    const response = await apiClient.get(`/user-stats/${userId}`, {
      headers: { 'Authorization': `Bearer ${token}` } // 带上 token 进行身份验证
    });

    return { success: true, stats: response.data.stats };
  } catch (error) {
    console.error('Error fetching user stats:', error);
    return { success: false, message: error.response?.data?.message || '获取统计信息失败' };
  }
};


// **查询用户单词笔记**
export const getUserNotes = async (userId, wordId) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      return { success: false, message: '请先登录' };
    }

    // 发送 GET 请求获取用户单词笔记
    const response = await apiClient.get(`/getNotes`, {
      params: { user_id: userId, word_id: wordId }, // 传递查询参数
      headers: { 'Authorization': `Bearer ${token}` } // 带上 token 进行身份验证
    });

    return { success: true, notes: response.data };
  } catch (error) {
    console.error('Error fetching user notes:', error);
    return { success: false, message: error.response?.data?.message || '获取单词笔记失败' };
  }
};


// **添加用户单词笔记**
export const addNote = async (userId, wordId, noteContent) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      return { success: false, message: '请先登录' };
    }

    // 发送 POST 请求添加用户的单词笔记
    const response = await apiClient.post(
      '/addNote',
      { user_id: userId, word_id: wordId, note: noteContent }, // 请求体传递的参数
      {
        headers: { 'Authorization': `Bearer ${token}` } // 带上 token 进行身份验证
      }
    );

    return { success: true, message: '笔记添加成功' };
  } catch (error) {
    console.error('Error adding user note:', error);
    return { success: false, message: error.response?.data?.message || '添加笔记失败' };
  }
};

// 删除用户笔记 API
export const deleteNoteApi = async (noteId) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      return { success: false, message: '请先登录' };
    }

    const response = await apiClient.delete(`/deleteNote/${noteId}`, {
      headers: { 'Authorization': `Bearer ${token}` }
    });

    return { success: true, message: response.data.message };
  } catch (error) {
    console.error('Error deleting note:', error);
    return { success: false, message: error.response?.data?.message || '删除笔记失败' };
  }
};

// 编辑笔记
export const editNoteApi = async (noteId, newContent) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      return { success: false, message: '请先登录' };
    }

    const response = await apiClient.put(`/editNote/${noteId}`,
      { note: newContent },
      {
        headers: { 'Authorization': `Bearer ${token}` }
      }
    );

    return { success: true, message: response.data.message };
  } catch (error) {
    console.error('Error updating note:', error);
    return { success: false, message: error.response?.data?.message || '更新笔记失败' };
  }
};


// 📁 src/api/signin.js

// 用户签到
export const userSignin = async (userId) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.post('/signin', { user_id: userId }, {
      headers: { Authorization: `Bearer ${token}` }
    });

    return { success: true, message: response.data.message };
  } catch (error) {
    return {
      success: false,
      message: error.response?.data?.message || '签到失败'
    };
  }
};

// 获取签到记录
export const getSigninRecords = async (userId) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.get(`/signin-records/${userId}`, {
      headers: { Authorization: `Bearer ${token}` }
    });

    return { success: true, records: response.data.records };
  } catch (error) {
    return {
      success: false,
      message: error.response?.data?.message || '获取签到记录失败'
    };
  }
};


// 获取用户需要复习的单词（支持分组数量）
export const getReviewWords = async (userId, limit) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.get('/review-words', {
      params: { user_id: userId, limit },
      headers: { 'Authorization': `Bearer ${token}` }
    });

    return { success: true, words: response.data.words };
  } catch (error) {
    console.error('获取复习单词失败:', error);
    return { success: false, message: error.response?.data?.message || '获取失败' };
  }
};
// 获取用户当前需要复习的单词数量
export const getReviewWordCount = async (userId) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.get('/review-word-count', {
      params: { user_id: userId },
      headers: { 'Authorization': `Bearer ${token}` }
    });

    return { success: true, count: response.data.count };
  } catch (error) {
    console.error('获取复习单词数量失败:', error);
    return { success: false, message: error.response?.data?.message || '获取失败' };
  }
};

// 批量更新单词的复习时间
export const updateReviewTime = async (userId, words) => {
  try {
    // console.log(userId, words, 'i看婆萨客场扑克牌萨科csaas');
    userId = parseInt(userId);
    // console.log(userId, words, 'i看婆萨客场扑克牌萨科');
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    // 检查必要参数是否存在
    if (!userId || !Array.isArray(words) || words.length === 0) {
      return { success: false, message: '缺少必要的参数' };
    }

    // 发送 POST 请求来更新复习时间
    const response = await apiClient.post(
      '/update-review-time',
      {
        userId,
        words
      },
      {
        headers: { 'Authorization': `Bearer ${token}` }
      }
    );

    return { success: true, message: response.data.message };
  } catch (error) {
    console.error('更新复习时间失败:', error);
    return { success: false, message: error.response?.data?.message || '服务器错误' };
  }
};

// 获取例句数据
export const getSentencesDataAPI = async () => {
  try {
    // 请求获取所有例句数据
    const response = await apiClient.get('/api/sentences');  // 请求新的接口 /api/sentences

    // 返回从接口获取到的数据
    return response.data;
  } catch (error) {
    console.error('获取例句数据失败:', error);
    return {
      success: false,
      message: error.response?.data?.message || '获取例句数据失败',
    };
  }
};


// 用单词id获取同义词和反义词
export const getSynonymsAntonymsByWordIdApi = async (wordId) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.get(`/api/words/${wordId}/synonyms-antonyms`, {
      headers: { 'Authorization': `Bearer ${token}` }
    });

    return {
      success: true,
      synonyms: response.data.synonyms,
      antonyms: response.data.antonyms
    };
  } catch (error) {
    console.error('获取同义词/反义词失败:', error);
    return { success: false, message: error.response?.data?.message || '获取失败' };
  }
};

// 获取所有单词的同义词和反义词
export const getAllSynonymsAntonymsApi = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.get('/api/words/all-synonyms-antonyms', {
      headers: { 'Authorization': `Bearer ${token}` }
    });

    return {
      success: true,
      synonyms: response.data.synonyms, // 结构为 { wordId: 'JSON字符串' }
      antonyms: response.data.antonyms
    };
  } catch (error) {
    console.error('获取所有同义词/反义词失败:', error);
    return { success: false, message: error.response?.data?.message || '获取失败' };
  }

};


// 获取所有单词的同义词和反义词
// 根据单词 ID 删除单词
export const DeleteWordDataByWordIdApi = async (wordId) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.delete(`/api/words/${wordId}`, {
      headers: { 'Authorization': `Bearer ${token}` }
    });

    return {
      success: true,
      message: response.data.message
    };
  } catch (error) {
    console.error('删除单词失败:', error);
    return {
      success: false,
      message: error.response?.data?.message || '删除失败'
    };
  }
};


// 更新单词数据的 API 路由
// 更新单词数据的 API 路由
export const updateWordByWordIdApi = async (wordId, updatedData) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.put(`/api/update-word-by-id/${wordId}`, updatedData, {
      headers: { 'Authorization': `Bearer ${token}` }
    });

    return {
      success: true,
      message: response.data.message
    };
  } catch (error) {
    console.error('更新单词失败:', error);
    return {
      success: false,
      message: error.response?.data?.message || '更新失败'
    };
  }
};
// 删除例句的接口
// 正确：删除例句的接口
export const deleteWordSentenceByIdApi = async (sentenceId) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.delete(`/api/word-sentences/${sentenceId}`, {
      headers: { 'Authorization': `Bearer ${token}` }
    });

    return {
      success: true,
      message: response.data.message
    };
  } catch (error) {
    console.error('删除例句失败:', error);
    return {
      success: false,
      message: error.response?.data?.message || '删除失败'
    };
  }
};
// 添加例句的接口
export const addWordSentenceApi = async (wordId, sentenceData) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.post(`/api/words/${wordId}/sentences`, sentenceData, {
      headers: { Authorization: `Bearer ${token}` }
    });

    return {
      success: true,
      message: response.data.message
    };
  } catch (error) {
    console.error('添加例句失败:', error);
    return {
      success: false,
      message: error.response?.data?.message || '添加失败'
    };
  }
};
// 更新例句的 API 函数
export const updateWordSentenceByIdApi = async (sentenceId, updatedData) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.put(`/api/UpdataWord-sentences/${sentenceId}`, updatedData, {
      headers: { Authorization: `Bearer ${token}` }
    });

    return {
      success: true,
      message: response.data.message
    };
  } catch (error) {
    console.error('更新例句失败:', error);
    return {
      success: false,
      message: error.response?.data?.message || '更新失败'
    };
  }
};

// 更新同义词的接口
// 更新同义词的接口
export const updateWordSynonymByIdApi = async (synonymId, updatedData) => {
  try {
    console.log(synonymId, updatedData);
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.put(`/api/update-word-synonyms/${synonymId}`, updatedData, {
      headers: { Authorization: `Bearer ${token}` }
    });
    return {
      success: true,
      message: response.data.message
    };
  } catch (error) {
    console.error('更新同义词失败:', error);
    return {
      success: false,
      message: error.response?.data?.message || '更新失败'
    };
  }
};

// 更新反义词的 API
export const updateWordAntonymByIdApi = async (antonymId, updatedData) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.put(`/api/update-word-antonyms/${antonymId}`, updatedData, {
      headers: { Authorization: `Bearer ${token}` }
    });

    return {
      success: true,
      message: response.data.message
    };
  } catch (error) {
    console.error('更新反义词失败:', error);
    return {
      success: false,
      message: error.response?.data?.message || '更新失败'
    };
  }
};

// 插入新单词
export const insertNewWordsApi = async (newWordData) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.post('/api/insertNewWords', newWordData, {
      headers: { Authorization: `Bearer ${token}` }
    });

    return {
      success: true,
      message: response.data.message
    };
  } catch (error) {
    console.error('插入单词失败:', error);
    return {
      success: false,
      message: error.response?.data?.message || '插入失败'
    };
  }
};


// 编辑单词接口调用
export const updateWordApi = async (newWordData) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    if (!newWordData?.id || !newWordData?.word) {
      return { success: false, message: 'id 和 word 字段不能为空' };
    }

    const response = await apiClient.post('/api/updateWord', newWordData, {
      headers: { Authorization: `Bearer ${token}` }
    });

    return {
      success: true,
      message: response.data.message
    };
  } catch (error) {
    console.error('更新单词失败:', error);
    return {
      success: false,
      message: error.response?.data?.message || '更新失败'
    };
  }
};









